package com.jianjun.project.system.dept;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.jfinal.aop.Before;
import com.jfinal.kit.Kv;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.SqlPara;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jianjun.common.constant.Constants;
import com.jianjun.common.constant.UserConstants;
import com.jianjun.common.exception.ServiceException;
import com.jianjun.common.util.SecurityUtils;
import com.jianjun.framework.web.domain.TreeSelect;
import com.jianjun.framework.web.interceptor.DataScopeInterceptor;
import com.jianjun.project.common.model.SysDept;
import com.jianjun.project.common.model.SysUser;
import com.jianjun.project.common.model.base.BaseSysDept;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 *
 * @author source
 */
public class SysDeptService {
    private final SysDept dao = new SysDept().dao();

    /**
     * 查询部门管理数据
     */
    public List<SysDept> selectDeptList(Model<SysDept> model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysDept", Kv.by("cond", model.toMap()).set(DataScopeInterceptor.getDataScope()));
        return dao.find(sqlParaDb);
    }

    public SysDept selectDeptFirst(Model<SysDept> model) {
        SqlPara sqlParaDb = Db.getSqlPara("querySysDept", Kv.by("cond", model.toMap()));
        return dao.findFirst(sqlParaDb);
    }

    /**
     * 查询部门树结构信息
     *
     * @param dept 部门信息
     * @return 部门树信息集合
     */
    public List<TreeSelect> selectDeptTreeList(SysDept dept) {
        List<SysDept> depts = selectDeptList(dept);
        return buildDeptTreeSelect(depts);
    }

    /**
     * 构建前端所需要树结构
     *
     * @param depts 部门列表
     * @return 树结构列表
     */
    public List<SysDept> buildDeptTree(List<SysDept> depts) {
        List<SysDept> returnList = new ArrayList<>();
        List<Long> tempList = depts.stream().map(SysDept::getDeptId).collect(Collectors.toList());
        for (SysDept dept : depts) {
            // 如果是顶级节点, 遍历该父节点的所有子节点
            if (!tempList.contains(dept.getParentId())) {
                recursionFn(depts, dept);
                returnList.add(dept);
            }
        }
        if (returnList.isEmpty()) {
            returnList = depts;
        }
        return returnList;
    }

    /**
     * 构建前端所需要下拉树结构
     *
     * @param depts 部门列表
     * @return 下拉树结构列表
     */
    public List<TreeSelect> buildDeptTreeSelect(List<SysDept> depts) {
        List<SysDept> deptTrees = buildDeptTree(depts);
        return deptTrees.stream().map(TreeSelect::new).collect(Collectors.toList());
    }


    /**
     * 根据部门ID查询信息
     *
     * @param deptId 部门ID
     * @return 部门信息
     */
    public SysDept selectDeptById(Long deptId) {
        return dao.findById(deptId);
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    public int selectNormalChildrenDeptById(Long deptId) {
        SysDept model = new SysDept();
        model.setStatus("0");
        model.setDelFlag("0");
        SqlPara sqlParaDb = Db.getSqlPara("selectChildrenDeptById", Kv.by("cond", model.toMap()).set("deptId", deptId));
        return Db.queryInt(sqlParaDb.getSql().replaceAll("(?<=select ).*\\*", "count(1)"), sqlParaDb.getPara());
    }

    /**
     * 是否存在子节点
     *
     * @param deptId 部门ID
     * @return 结果
     */
    public boolean hasChildByDeptId(Long deptId) {
        SysDept model = new SysDept();
        model.setParentId(deptId);
        SqlPara sqlParaDb = Db.getSqlPara("querySysDept", Kv.by("cond", model.toMap()));
        return Db.queryInt(sqlParaDb.getSql().replaceAll("(?<=select ).*\\*", "count(1)"), sqlParaDb.getPara()) > 0;
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    public boolean checkDeptExistUser(Long deptId) {
        SysUser model = new SysUser();
        model.setDeptId(deptId);
        SqlPara sqlParaDb = Db.getSqlPara("querySysUser", Kv.by("cond", model.toMap()));
        return Db.queryInt(sqlParaDb.getSql().replaceAll("(?<=select ).*\\*", "count(1)"), sqlParaDb.getPara()) > 0;
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    public boolean checkDeptNameUnique(SysDept dept) {
        long deptId = Objects.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        SysDept model = new SysDept();
        model.setDeptName(dept.getDeptName());
        model.setParentId(dept.getParentId());
        SysDept info = selectDeptFirst(model);
        if (Objects.nonNull(info) && info.getDeptId() != deptId) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }


    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId()) && Objects.nonNull(deptId)) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = selectDeptList(dept);
            if (CollectionUtil.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    public boolean insertDept(SysDept dept) {
        SysDept info = dao.findById(dept.getParentId());
        // 如果父节点不为正常状态,则不允许新增子节点
        if (!UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        dept.setAncestors(info.getAncestors() + Constants.DELIMETER + dept.getParentId());
        dept.setCreateTime(new Date());
        return dept.save();
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Before(Tx.class)
    public boolean updateDept(SysDept dept) {
        SysDept newParentDept = dao.findById(dept.getParentId());
        SysDept oldDept = dao.findById(dept.getDeptId());
        if (Objects.nonNull(newParentDept) && Objects.nonNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + Constants.DELIMETER + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        dept.setUpdateTime(new Date());
        boolean result = dept.update();
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StrUtil.isNotEmpty(dept.getAncestors())
                && !"0".equals(dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        String ancestors = dept.getAncestors();
        Long[] deptIds = Convert.toLongArray(ancestors);
        Db.template("updateDeptStatusNormal", Kv.of("deptIds", deptIds)).update();
    }

    /**
     * 修改子元素关系
     *
     * @param deptId 被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    public void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = dao.template("selectChildrenDeptById", Kv.by("deptId", deptId)).find();
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (!children.isEmpty()) {
            Db.template("updateDeptChildren", Kv.of("deptIds", children.stream().map(BaseSysDept::getDeptId).collect(Collectors.toList()))
                    .set("ancestors", children.stream().map(BaseSysDept::getAncestors).collect(Collectors.toList()))).update();
        }
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    public int deleteDeptById(Long deptId) {
        SysDept model = new SysDept();
        model.setDeptId(deptId);
        return Db.template("deleteDept", Kv.of("cond", model.toMap())).update();
    }

    /**
     * 递归列表
     */
    private void recursionFn(List<SysDept> list, SysDept t) {
        // 得到子节点列表
        List<SysDept> childList = getChildList(list, t);
        t.setChildren(childList);
        for (SysDept tChild : childList) {
            if (hasChild(list, tChild)) {
                recursionFn(list, tChild);
            }
        }
    }

    /**
     * 得到子节点列表
     */
    private List<SysDept> getChildList(List<SysDept> list, SysDept t) {
        List<SysDept> tlist = new ArrayList<>();
        for (SysDept n : list) {
            if (Objects.nonNull(n.getParentId()) && n.getParentId().longValue() == t.getDeptId().longValue()) {
                tlist.add(n);
            }
        }
        return tlist;
    }

    /**
     * 判断是否有子节点
     */
    private boolean hasChild(List<SysDept> list, SysDept t) {
        return !getChildList(list, t).isEmpty();
    }
}
